package com.xxkk.spring_boot_web.sdk.XnetPay;

/**
 * 签名用的工具
 */

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.codec.digest.DigestUtils;

public class SignUtil {

    /**
     * 生成签名字符串
     **/
    public static String buildSign(Map<String, String> map, String key) {
        StringBuilder buf = new StringBuilder((map.size() + 1) * 10);
        buildPayParams(buf, map, false);
        String preStr = buf.toString();
        return sign(preStr, "&key=" + key, "utf-8").toUpperCase();
    }


    public static String sign(String text, String key, String input_charset) {
        text = text + key;
        System.out.println("MD5 前字段：" + text);
        return DigestUtils.md5Hex(getContentBytes(DigestUtils.md5Hex(getContentBytes(text, input_charset)), input_charset));
    }

    public static void buildPayParams(StringBuilder sb, Map<String, String> payParams, boolean encoding) {
        List<String> keys = new ArrayList<String>(payParams.keySet());
        Collections.sort(keys);
        for (String key : keys) {
            String value = payParams.get(key);
            if (!"sign".equals(key) && value != null && !value.equals("")) {
                sb.append(key).append("=");
                if (encoding) {
                    try {
                        sb.append(URLEncoder.encode(value, "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                } else {
                    sb.append(payParams.get(key));
                }
                sb.append("&");
            }
        }
        sb.setLength(sb.length() - 1);
    }

    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

    /**
     * 签名验证
     **/
    public static boolean verify(Map<String, String> params, String signkey) {
        String sign = (String) params.get("sign");
        String verifySign = buildSign(params, signkey);
        if (verifySign.equals(sign)) {
            return true;
        } else {
            System.out.println(" verify failed" + params.toString());
        }
        return false;
    }
}
